package com.wsc.frontier;


import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import com.wsc.frontier.database.DataBaseDetails;

/**
 *
 * @author N V Reddy
 */
public class FSSupport {
	
    public String sendURLs(){
    	Date dt = new Date();
		Timer t = new Timer();
		DateFormat df = new SimpleDateFormat("yyyy-mm-dd-hh-mm-ss");
		String sendfilename = "temppath"+"sendurl"+df.format(dt)+".xml";
		
    	Connection con;
     	String url= DataBaseDetails .getJdbcUrl();
 		String database = DataBaseDetails .getDatabaseName();
 		String driver = DataBaseDetails .getDatabaseDriver();
 		String user = DataBaseDetails .getDatabaseUser();
 		String password = DataBaseDetails .getDatabasePassword(); 
 		String urlname,ip;
		int count;
		
		try{
 			Class.forName(driver);
 		  	con=DriverManager.getConnection(url+database,user,password);
		  	Statement st = con.createStatement();
		  	ResultSet res = st.executeQuery("SELECT count(*) FROM `urllist`");
		  	res.next();
		  	count = res.getInt(1);
		  	DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		  	DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
		  	Document doc = docBuilder.newDocument();
		  	
		  	if(count>100){
		  		count =100;
		  	}
		  	
		  	Element urllist = doc.createElement("urllist");
			doc.appendChild(urllist);
			res = st.executeQuery("SELECT * FROM `urllist` LIMIT "+count);
			while(res.next()){
		  		urlname = res.getString(1);
		  		ip	= res.getString(2);
		  		
		  		//urldetails+ child of urllist
			  	Element urldetails = doc.createElement("urldetails");
			  	urllist.appendChild(urldetails);
			  	
			  	//urlnam child of urldetails
			  	Element url_name = doc.createElement("urlname");
			  	url_name.appendChild(doc.createTextNode(urlname));
			  	urldetails.appendChild(url_name);
			  		
			  	//urlip child of urldetails
			  	Element url_ip = doc.createElement("urlip");
			  	url_ip.appendChild(doc.createTextNode(ip));
			  	urldetails.appendChild(url_ip);
		  	}

		  	TransformerFactory transformerFactory = TransformerFactory.newInstance();
		  	Transformer transformer = transformerFactory.newTransformer();
		  	transformer.setOutputProperty(OutputKeys.INDENT,"yes");
			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(new File(sendfilename));
			transformer.transform(source, result);
			System.out.println("File saved");
			st.executeUpdate("DELETE FROM `urllist` LIMIT "+count);
		  	return sendfilename;
		}
		catch(Throwable tt){
			System.out.println("not processed"+tt);
			return null;
		}

    }
    
    public void takeURLs(String filename){
    	try {
        	String url_name,url_ip;
        	Connection con;
    		String url= DataBaseDetails .getJdbcUrl();
    		String database = DataBaseDetails .getDatabaseName();
    		String driver = DataBaseDetails .getDatabaseDriver();
    		String user = DataBaseDetails .getDatabaseUser();
    		String password = DataBaseDetails .getDatabasePassword();
    	  	Class.forName(driver);
    	  	con=DriverManager.getConnection(url+database,user,password);
    	  	
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(filename);
	        doc.getDocumentElement().normalize();
		        
	        NodeList nList = doc.getElementsByTagName("url");
	        for (int temp = 0; temp < nList.getLength(); temp++) {
	        	Node nNode = nList.item(temp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
					url_name = eElement.getElementsByTagName("name").item(0).getTextContent();
                    url_ip = eElement.getElementsByTagName("ip").item(0).getTextContent();
                    //database insertion
                    
                    PreparedStatement pst = con.prepareStatement("insert into `urllist` (`url`,`ip`)"+ " values(?,?);");
                    pst.setString(1, url_name);
                    pst.setString(2, url_ip);
                    pst.executeUpdate();
                    System.out.println("insertion successful");
            
                }//end of if clause
		    }
                        
            
            }catch (SAXParseException err) {
            System.out.println ("** Parsing error" + ", line " 
                 + err.getLineNumber () + ", uri " + err.getSystemId ());
            System.out.println(" " + err.getMessage ());

            }catch (SAXException e) {
            Exception x = e.getException ();
            ((x == null) ? e : x).printStackTrace ();

            }catch (Throwable t) {
            t.printStackTrace ();
            }

    }
}
